using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Systems.Security;
using Deepcode.Flux.Core.Systems.Audit;
using Deepcode.Flux.Core.Systems.Audit.Quick;

public partial class Private_Config_Event_menu : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxGeneralAdmin"; } }
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			SetupSearchForm();
			RebindTreeData();
		}
	}
	#endregion
	#region Search Form
	/// <summary>
	/// Populate the various drop down lists etc
	/// </summary>
	private void SetupSearchForm()
	{
		GetUserList();
		GetTypeList();
		GetSeverityList();
		GetClasses();
		GetApplications();

		txtFromDate.Text = "1 Jan 1990";
		txtToDate.Text = System.DateTime.Now.ToString("d MMM yyyy");
	}
	/// <summary>
	/// Populate the user's drop down list
	/// </summary>
	private void GetUserList()
	{
		AdministrationUsers users = new AdministrationUsers();
		
		ddlUser.Items.Clear();
		ddlUser.Items.Add( new ListItem( "All users", "0" ));
		ddlUser.Items.Add( new ListItem( "System User", "-1"));
		foreach (AdministrationUser user in users.GetAllUsers(AdministrationUsersSortOrder.RealName))
			ddlUser.Items.Add( new ListItem( user.RealName, user.PK_ID.ToString() ));
	}
	/// <summary>
	/// Populates the list of event types
	/// </summary>
	private void GetTypeList()
	{
		ddlEventType.Items.Clear();
		ddlEventType.Items.Add( new ListItem( "All types", SearchEventType.All.ToString() ));
		ddlEventType.Items.Add( new ListItem( "System events", SearchEventType.System.ToString() ));
		ddlEventType.Items.Add( new ListItem( "Security events" , SearchEventType.Security.ToString() ));
		ddlEventType.Items.Add( new ListItem( "Application events", SearchEventType.Application.ToString() ));
	}
	/// <summary>
	/// Populates the list of severities
	/// </summary>
	private void GetSeverityList()
	{
		ddlSeverity.Items.Clear();
		ddlSeverity.Items.Add( new ListItem( "Trace and above", EventSeverity.Trace.ToString() ));
		ddlSeverity.Items.Add( new ListItem( "Information and above", EventSeverity.Information.ToString() ));
		ddlSeverity.Items.Add( new ListItem( "Important and above", EventSeverity.Important.ToString() ));
		ddlSeverity.Items.Add( new ListItem( "Critical and above", EventSeverity.Critical.ToString() ));
		ddlSeverity.Items.Add( new ListItem( "Error and above", EventSeverity.Error.ToString() ));
	}
	/// <summary>
	/// Populates the list of available classes
	/// </summary>
	private void GetClasses()
	{
		SystemEvents events = new SystemEvents();
		
		ddlClass.Items.Clear();
		ddlClass.Items.Add( new ListItem( "All Classes", "" ));

		foreach( string EventClass in events.GetEventClasses() )
			ddlClass.Items.Add( new ListItem( EventClass, EventClass ));
	}
	/// <summary>
	/// Populates the list of applications
	/// </summary>
	private void GetApplications()
	{
		SystemEvents events = new SystemEvents();
		
		ddlApplication.Items.Clear();
		ddlApplication.Items.Add( new ListItem( "All Applications", "" ));

		foreach( string EventApplication in events.GetAllApplicationClasses() )
			ddlApplication.Items.Add( new ListItem( EventApplication, EventApplication ));
	}
	#endregion
	#region Configuration
	/// <summary>
	/// User has changed whether event types should be grouped
	/// by type (system, security, application) or not.
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void GroupTypesCheckChange(object sender, EventArgs e)
	{
		RebindTreeData();
	}
	#endregion
	#region Tree data binding
	/// <summary>
	/// Data binder
	/// </summary>
	private void RebindTreeData()
	{
		if( chkGroupTypes.Checked ) RebindGrouped();
		else RebindUngrouped();
	}
	/// <summary>
	/// Gets the tree data, grouped by event types
	/// IE:
	///		Type					(System, Security or Application)
	///			Class				(The class of the event - eg: Flux)
	///				Application		(The application - eg: Security Login)
	/// </summary>
	private void RebindGrouped()
	{
		navTree.Nodes.Clear();
		
		// System events node
		TreeNode NodeSystem = new TreeNode();
		NodeSystem.Target = "ReportFrame";
		NodeSystem.NavigateUrl = GetNodeURL(SearchEventType.System, "", "");
		NodeSystem.Text = "System Events";
		NodeSystem.Expanded = false;
		navTree.Nodes.Add( NodeSystem );
		BindEventClassesTo( NodeSystem.ChildNodes, EventType.System );

		// Security events node
		TreeNode NodeSecurity = new TreeNode();
		NodeSecurity.Target = "ReportFrame";
		NodeSecurity.NavigateUrl = GetNodeURL(SearchEventType.Security, "", "");
		NodeSecurity.Text = "Security Events";
		NodeSecurity.Expanded = false;
		navTree.Nodes.Add(NodeSecurity);
		BindEventClassesTo(NodeSecurity.ChildNodes, EventType.Security);

		// Application events node
		TreeNode NodeApplication = new TreeNode();
		NodeApplication.Target = "ReportFrame";
		NodeApplication.NavigateUrl = GetNodeURL(SearchEventType.Application, "", "");
		NodeApplication.Text = "Application Events";
		NodeApplication.Expanded = false;
		navTree.Nodes.Add(NodeApplication);
		BindEventClassesTo(NodeApplication.ChildNodes, EventType.Application);
	}
	/// <summary>
	/// Gets the tree data, not grouped by event types
	/// IE:
	///		Class				(The class - eg: Flux)
	///			Application		(The application - eg: Security Login)
	/// </summary>
	private void RebindUngrouped()
	{
		navTree.Nodes.Clear();
		BindEventClassesTo(navTree.Nodes);
	}
	/// <summary>
	/// Gets the navigational tree data without grouping by type
	/// </summary>
	/// <param name="nodes"></param>
	private void BindEventClassesTo(TreeNodeCollection nodes)
	{
		SystemEvents Events = new SystemEvents();
		string [] EventClasses = Events.GetEventClasses();
		if( EventClasses == null ) return;

		foreach (string EventClass in EventClasses)
		{
			TreeNode node = new TreeNode();
			node.Target = "ReportFrame";
			node.NavigateUrl = GetNodeURL(SearchEventType.All, EventClass, "");
			node.Text = EventClass;
			node.Expanded = false;
			nodes.Add(node);

			string[] ApplicationClasses = Events.GetApplicationClassesInEventClass(EventClass);
			if (ApplicationClasses != null)
			{
				foreach (string ApplicationClass in ApplicationClasses)
				{
					TreeNode node2 = new TreeNode();
					node2.Target = "ReportFrame";
					node2.NavigateUrl = GetNodeURL(SearchEventType.All, EventClass, ApplicationClass);
					node2.Text = ApplicationClass;
					node2.Expanded = false;
					node.ChildNodes.Add(node2);
				}
			}
		}
	}
	/// <summary>
	/// Gets the navigational tree data, filtered by type
	/// </summary>
	/// <param name="nodes"></param>
	/// <param name="FilterType"></param>
	private void BindEventClassesTo(TreeNodeCollection nodes, EventType FilterType)
	{
		SystemEvents Events = new SystemEvents();
		string [] EventClasses = Events.GetEventClassesInType(FilterType);
		if( EventClasses == null ) return;

		foreach (string EventClass in EventClasses)
		{
			TreeNode node = new TreeNode();
			node.Target = "ReportFrame";
			node.NavigateUrl = GetNodeURL( (SearchEventType) FilterType, EventClass, "");
			node.Text = EventClass;
			node.Expanded = false;
			nodes.Add(node);

			string[] ApplicationClasses = Events.GetApplicationClassesInEventClassForType( EventClass, FilterType );
			if (ApplicationClasses != null)
			{
				foreach (string ApplicationClass in ApplicationClasses)
				{
					TreeNode node2 = new TreeNode();
					node2.Target = "ReportFrame";
					node2.NavigateUrl = GetNodeURL((SearchEventType) FilterType, EventClass, ApplicationClass);
					node2.Text = ApplicationClass;
					node2.Expanded = false;
					node.ChildNodes.Add(node2);
				}
			}
		}
	}
	/// <summary>
	/// Gets the URL necessary to open a report based on 
	/// navigation selections of type, class and application.
	/// </summary>
	/// <param name="type"></param>
	/// <param name="Class"></param>
	/// <param name="Application"></param>
	/// <returns></returns>
	private string GetNodeURL(SearchEventType type, string Class, string Application)
	{
		string sType = "";
		if (type != SearchEventType.All) sType = type.ToString();
		return String.Format("report.aspx?type={0}&class={1}&application={2}", sType, Class, Application);
	}
	#endregion
	#region User interaction
	/// <summary>
	/// User is attempting a cleardown
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnClearDown_Clicked(object sender, EventArgs e)
	{
		if (!Page.IsValid) return;
	
		SystemEvents events = new SystemEvents();
		if (txtClearBefore.Text == "")
		{
			events.ClearLogs();
			QuickAudit.RaiseImportant(new AuditUser(), "Flux", "Event viewer", "cleared down the entire event log");
		}			
		else
		{
			events.ClearLogsBefore( txtClearBefore.DateTimeValue );
			QuickAudit.RaiseImportant( new AuditUser(), "Flux", "Event viewer", "cleared down the event logs up to {0}", txtClearBefore.DateTimeValue.ToShortDateString());
		}
		RebindTreeData();
	}
	/// <summary>
	/// User has requested a search against the events data
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnSearchGo_Clicked(object sender, EventArgs e)
	{
		string script = ("<script language=javascript>");
		script += String.Format("LaunchSearch('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');",
			txtSearchText.Text,
			ddlUser.SelectedValue,
			ddlEventType.SelectedValue,
			ddlSeverity.SelectedValue,
			ddlClass.SelectedValue,
			ddlApplication.SelectedValue,
			txtFromDate.Text,
			txtToDate.Text);

		script += "</script>";

		Page.ClientScript.RegisterStartupScript(
			this.GetType(),
			"",
			script);
	}
	#endregion
}
